package com.twp.auth.config.auth;

import com.twp.common.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import com.twp.auth.security.*;

import javax.sql.DataSource;


@Configuration
@EnableAuthorizationServer
//@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true)
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private DataSource eepDatasource;

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    AuthConfig authConfig;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(eepDatasource);
    }

    @ConditionalOnExpression("${auth.isLogout:false}")
    @Primary
    @Bean
    public MyTokenServices fsTokenServices(TokenStore tokenStore){
        MyTokenServices fsTokenServices = new MyTokenServices(tokenStore,clientDetailsService);
        fsTokenServices.setTokenStore(tokenStore);
        fsTokenServices.setClientDetailsService(clientDetailsService);
        fsTokenServices.setSupportRefreshToken(true);
        return fsTokenServices;
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // @formatter:off
        TokenStore tokenStore = tokenStore();
        if (authConfig.isLogout()){
            endpoints.tokenServices(fsTokenServices(tokenStore));
        }
        endpoints
                .tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)

        ;
        // @formatter:on
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        final int[] index={0};
        authConfig.getClients()
                .stream()
                .map(c->c.withIndex(index[0]++))
                .forEach(client ->{
                    ClientDetailsServiceBuilder.ClientBuilder clientBuilder = builder
                            .withClient(client.getClientName())
                            .secret(client.getSecret())
                            .authorizedGrantTypes(client.getAuthorizedGrantTypes())
                            .scopes(client.getScopes())
                            .accessTokenValiditySeconds(client.getAccessTokenValiditySeconds());
                    if (index[0] < authConfig.getClients().size()){
                        clientBuilder.and();
                    }
                 }
                );

    }
}
